import { Component, OnInit, ViewChild } from '@angular/core';
import { ColumnType, SPage, TablePageComponent } from '@shared/components/table-page/table-page.component';
import { Body, _HttpClient } from '@delon/theme';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { DeviceEditComponent } from '../device-edit/device-edit.component';
import { PersonEditComponent } from '../person-edit/person-edit.component';
import { BindRoomComponent } from '../bind-room/bind-room.component';
import { ApiService } from '@core/services/api';
import { STData } from '@delon/abc';
import { Md5 } from 'ts-md5';
import { ACLService } from '@delon/acl';
import { DeviceSetBatchComponent } from '../device-set-batch/device-set-batch.component';
import { PwdSetComponent } from '../pwd-set/pwd-set.component';
import { UploadTxtComponent } from '../upload-txt/upload-txt.component';

@Component({
  selector: 'device-list',
  templateUrl: './device-list.component.html',
  styleUrls: []
})
export class DeviceListComponent implements OnInit {
  @ViewChild('st', { static: false }) st: TablePageComponent;
  bindFlag:boolean = this.aclService.canAbility("device-list/bind");//检查用户按钮权限
  detailFlag:boolean =  this.aclService.canAbility("device-list/detail");
  pwdFlag:boolean =  this.aclService.canAbility("device-list/pwd");
  selectData: any;
  loading = false;
  addUserInfo = {
    userAccount: '',
    userPassword: '',
    userName: '',
    roles: [],
    depts: []
  };
  config: SPage = {
    columns: [
      {
        index:"",
        title:"选择",
        type:ColumnType.checkbox
      },
      {
        index: 'deviceCode',
        title: '设备SN码',
        width:150,
        filter: {
          placeholder: '请输入设备SN码',
          type: 'string'
        }
      },
      {
        index: 'deviceDescribe',
        title: '设备描述',
        width:100,
        filter: {
          placeholder: '请输入设备描述',
          type: 'string'
        }
      },
      {
        index: 'deviceFac',
        title: '设备厂商',
        width:100,
        filter: {
          placeholder: '请输入厂商',
          type: 'string'
        }
      },
      {
        index:'deviceCategory',
        title:'设备类型',
        width:100,
        type: ColumnType.tag,
        tag: {
          1:{text: '大门口机'},
          2:{text: '管理机'},
          3:{text: '单元机'},
          4:{text:'室内机'}
        },
      },
      {
        index: 'deviceType',
        title: '设备分类',
        width:100,
        type: ColumnType.tag,
        tag:{
          1:{text: '门禁摄像机'},
          2:{text: '门禁刷卡'},
          3:{text: 'IPC'},
          4:{text: 'NVR'},
          5:{text: '微型门禁产品'},
          6:{text: '安卓门禁产品'},
          7:{text: '门铃'},
          8:{text: '4G开门控制器'},
          12:{text: 'linux人脸机'}
          
        },
        filter: {
          placeholder: '请选择设备分类',
          type: 'select',
          items: [
            {label: '门禁摄像机', value: 1},
            {label: '门禁刷卡', value: 2},
            {label: 'IPC', value: 3},
            {label: 'NVR', value: 4},
            {label: '微型门禁产品', value: 5},
            {label: '安卓门禁产品', value: 6},
            {label: '门铃', value: 7},
            {label: '4G开门控制器',value: 8},
            {label: 'linux人脸机',value: 12}
          ]
        }
      },
      {
        index: 'deviceLocation',
        title: '安装地址',
        width:450,
        filter: {
          placeholder: '请输入安装地址',
          type: 'string'
        },
        //className:'w200'
      },
      {
        index: 'deviceLocationStatus',
        title: '绑定状态',
        width:100,
        type: ColumnType.tag,
        tag: {
          0:{text: '未绑定',color: 'red'},
          1:{text: '已绑定',color: 'green'}
        },
        filter: {
          placeholder: '请选择绑定状态',
          type: 'select',
          items: [
            {label: '未绑定', value: 0},
            {label: '已绑定', value: 1},
          ]
        }
      },
      {
        index: 'deviceLastStatus',
        title: '设备状态',
        width:100,
        type: ColumnType.tag,
        tag:{
          0:{text: '离线',color: 'red'},
          1:{text: '在线',color: 'green'}
        },
        filter: {
          placeholder: '请选择设备状态',
          type: 'select',
          items: [
            {label: '离线', value: 0},
            {label: '在线', value: 1},
          ]
        }
      },
      {
        index: 'deviceIp',
        title: '门禁IP',
        width:120,
        filter:{
          placeholder:'请输入设备IP地址',
          type:'string'
        }
      },
      {
        index: 'status',
        title: '状态',
        width:80,
        type: ColumnType.tag,
        tag:{
          true:{text:'启用',color:'green'},
          false:{text:'停用',color:'red'}
        }
      },
      {
        index: '',
        title: '操作',
        width:240,
        fixed:'right',
        buttons:[
          {
            text:'详情',
            iif:()=>{
              return this.detailFlag;
            },
            click:(_record)=>{
              this.editDic(1, _record);
            }
          },
          {
            text:'绑定',
            iif: (data: STData) => {
                  return data.deviceLocationStatus == 0 && this.bindFlag;
               },
            click:(_record)=>{
              this.bindroom(_record);
            }
          },
          {
            text:'设置密码',
            iif:()=>{
              return this.pwdFlag;
            },
            click:(_record)=>{
              // let pwd=this.getPwd(_record.deviceCode);
              // this.sendPwd(_record.deviceCode,_record.deviceType,pwd);
              if(_record.deviceLastStatus != 1){
                this.message.error("设备不在线!")
                return
              }
              const modal = this.modal.create({
                nzTitle: '设置密码',
                nzContent: PwdSetComponent,
                nzWidth: 800,
                nzComponentParams: {
                  _record
                },
                nzOnOk: () => {
                  this.st.reload()
                },
                nzFooter: null
              })
              modal.afterClose.subscribe(res => {
                if (res === 'ok') {
                  this.st.reload()
                }
              })
            }
          },
          {
            text:'删除',
            // iif: (data: STData) => {
            //       return data.deviceLocationStatus == 0 && this.bindFlag;
            //    },
            click:(_record)=>{
              this.delDevice(_record.id);
            }
          },
        ]
      },
    ],
    showCheckBox: false,
    reqUrl:'/core/host/page',
    defaultParam:{status:true}
    // editBtn: [
    //   { title: '详情' },
    //   // {title: '禁用'},
    //   // {title: '责任人'},
    //   {title: '绑定',
    //   iif: (data: STData) => {
    //     return data.deviceLocationStatus == 0
    //   } }
    // ]
  }
  constructor(private http: _HttpClient,  private api: ApiService, private modal: NzModalService, private message: NzMessageService,private aclService: ACLService) { }
  
  ngOnInit() {

  }

  //将临时密码传到后台
  sendPwd(deviceCode,deviceType,pwd){
    this.http.post("/core/host/remoteOpen",{deviceCode:deviceCode,deviceType:deviceType,password:pwd}).subscribe((res:any) => {
    })
  }

  //生成临时密码
  getPwd(id:string){
    let timeSn= Md5.hashStr(this.getTimeStamp()+id);
      //console.log(timeSn);
      //截取加密后的数据
      let subData=timeSn.substring(8,24);
      //console.log(subData);
      //取高位之后的数据
      let hightData=this.getMd5Data(subData);
      //console.log(hightData);
      //16进制转为10进制
      let tenData=parseInt(hightData,16)+"";
      //console.log(tenData);
     //如果不足6位，则补0
      if(tenData.length < 6){
        let num = 6 - tenData.length;
       for(let i=0;i<num;i++){
         tenData="0"+tenData;
       }
      }
       //截取后六位
      let pwd=tenData.substring(tenData.length-6,tenData.length);
      return pwd;
  }

  //获取当前时间戳，到小时
  getTimeStamp(){
    let date=new Date();
    let year=date.getFullYear();
    let month : any =date.getMonth()+1;
    let day : any =date.getDate();
    let h : any =date.getHours();
    month = month < 10 ? "0"+month : month;
    day = day < 10 ? "0"+day : day;
    h = h < 10 ? "0" + h : h;
    let res=year+month+day+h;
    return res;
  }
//加密后的数据取高位
getMd5Data(str:string) : string{
    let arr=str.split("");
    let str2="";
    for(let i=0;i<arr.length;i++){
      if(i % 2 == 0){
        str2+=arr[i];
      }
    }
    return str2;
}



  // 编辑功能开始
  editDic(type: 0 | 1 = 0, _param?: object): void {
    console.log(type);
    const title = type ? '设备详情':'新增设备';
    const modal = this.modal.create({
      nzTitle: title,
      nzContent: DeviceEditComponent,
      nzWidth: 1300,
      nzComponentParams: {
        type,
        _param
      },
      nzOnOk: () => {
        this.st.reload();
      },
      nzFooter: null
    })
    modal.afterClose.subscribe(res => {
      if (res === 'ok') {
        this.st.reload();
      }
    })
  }
  //禁用设备
  disAble(param:number):void{
    console.log(param);
    const body = [];
    body.push({id:param,status:false});
    this.http.put('/core/host/batch',body).subscribe(res => {
      if(res.status === '200'){
        this.message.success('禁用成功');
        this.st.reload();
      }
    })
  }
  //删除设备
  delDevice(id):void{
    this.modal.confirm({
      nzTitle:"确定删除?",
      nzOnOk: ()=>{
        this.http.put("/core/host/forbidden",[{id:id,status:false}]).subscribe((res:any) => {
          if (res.status === '200') {
            this.message.success(res.message);
            this.st.reload();
          }else{
            this.message.error(res.message);
          }
        })
      }
    })
  }
  //责任人
  person(_param:object):void {
    const modal = this.modal.create({
      nzTitle: '责任人',
      nzContent: PersonEditComponent,
      nzWidth: 800,
      nzComponentParams: {
        _param
      },
      nzOnOk: () => {
        this.st.reload();
      },
      nzFooter: null
    })
  }

  //绑定房间
  bindroom(_param:object):void {
    const modal = this.modal.create({
      nzTitle: '添加绑定',
      nzContent: BindRoomComponent,
      nzWidth: 800,
      nzComponentParams: {
        _param
      },
      nzOnOk: () => {
        this.st.reload();
      },
      nzFooter: null
    })
  }

  operate(e: any): void {
    if (e.title === '详情') {
      this.editDic(1, e.data);
    }
    if(e.title === '禁用'){
      this.disAble(e.data.id);
    }
    if(e.title === '责任人'){
      this.person(e.data);
    }
    if(e.title === '绑定'){
      this.bindroom(e.data);
    }
  }
  _console(e: any): void {
    this.selectData = e;
  }
  dataProcess(data: STData[]){
    console.log(data);
    for(let item of data){
      item.deviceFac="兴天下";
    }
    return data;
  }
  //禁用多人
  disAbleAll() {
    if (!!this.selectData && this.selectData.length !== 0) {
      this.modal.confirm({
        nzTitle: '您确定要禁用这些数据吗',
        nzOnOk: () => {
          const body = [];
          this.selectData.forEach(item => {
            body.push({id:item.id,status:false});
          })
          this.http.put('/core/host/batch',body).subscribe(res => {
            if(res.status === '200'){
              this.message.success('禁用成功');
              this.st.reload();
            }
          })
        }
      })
    } else {
      this.message.warning('请选择数据');
    }
  }
 
 
  //批量设置
  setBatch(){
    if(this.selectData == undefined){
      this.message.error("请选择设备!");
      return;
    }
    let arr=[];
    this.selectData.forEach(item=>{
      arr.push(item.deviceType)
    })
    for(let i=0;i<arr.length-1;i++){
      if(arr[i] != arr[i+1]){
        this.message.error("请选择相同类型的设备!")
        return
      }
    }
    const modal = this.modal.create({
      nzTitle: "批量设置",
      nzContent: DeviceSetBatchComponent,
      nzWidth: 1300,
      nzComponentParams: {
        _param:this.selectData
      },
      nzOnOk: () => {
        this.st.reload();
      },
      nzFooter: null
    })
  }
   //下发txt文件
   sendTxt(){
    if(this.selectData == undefined){
      this.message.error("请选择设备!");
      return;
    }
    let arr=[];
    this.selectData.forEach(item=>{
      arr.push(item.deviceCode)
    })
    const modal = this.modal.create({
      nzTitle: "下发txt文件",
      nzContent: UploadTxtComponent,
      nzWidth: 600,
      nzComponentParams: {
        arr,
      },
      nzOnOk: () => {
        this.st.reload();
      },
      nzFooter: null
    })
    modal.afterClose.subscribe(res => {
      if (res === 'ok') {
        this.st.reload();
      }
    })
  }
}
